package cn.pzhuweb.util;

import cn.pzhuweb.pojo.Message;
import org.apache.commons.mail.SimpleEmail;

import java.security.SecureRandom;
import java.util.Random;

/**
 * @author Yancy xiao
 * @create 2022-11-29 10:19
 */
public class EmailUtil {
    public static Message sendEmail(String email) {
        SimpleEmail simpleEmail = new SimpleEmail();
        simpleEmail.setHostName("smtp.qq.com");
        simpleEmail.setSslSmtpPort("465");
        simpleEmail.setAuthentication("209195687@qq.com", "nbuyrqkeiqhkcage");
        try {
            simpleEmail.addTo(email);
            simpleEmail.setFrom("209195687@qq.com", "Yancy");
            simpleEmail.setSubject("Java Web验证码");
            String code = randomCode();
            simpleEmail.setMsg("你的邮箱验证码是："+ code);
            simpleEmail.send();
            return new Message(true, code);
        } catch (Exception e) {
            return new Message(false, "邮件发送失败!");
        }
    }

    private static String randomCode() {
        char[] eles = "23456789qwertyupasdfghjkzxcvbnmQWERTYUPASDFGHJKZXCVBNM".toCharArray();
        Random random = new SecureRandom();
        String code = "";
        for (int i = 0; i < 4; i++) {
            char ele = eles[random.nextInt(eles.length)];
            code += ele;
        }
        return code;
    }
}
